package leetcode.code1905;

public class Solution extends Solution1905 {

	private int row;
	private int col;

	@Override
	public int countSubIslands(int[][] grid1, int[][] grid2) {
		row = grid1.length;
		col = grid1[0].length;
		int ans = 0;
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				if (grid1[i][j] == 1 && grid2[i][j] == 1) {
					ans += this.infect(grid1, grid2, i, j) ? 1 : 0;// 完全覆盖+1，未完全覆盖+0
				}
			}
		}
		return ans;
	}

	// 与 grid2[i][j] 相连的陆地是否完全被 grid1覆盖
	private boolean infect(int[][] grid1, int[][] grid2, int i, int j) {
		if (i >= 0 && i < row && j >= 0 && j < col) {
			if (grid2[i][j] == 1) {
				grid2[i][j] = 2;
				boolean b1 = this.infect(grid1, grid2, i + 1, j);
				boolean b2 = this.infect(grid1, grid2, i - 1, j);
				boolean b3 = this.infect(grid1, grid2, i, j + 1);
				boolean b4 = this.infect(grid1, grid2, i, j - 1);
				if (grid1[i][j] == 0 || !b1 || !b2 || !b3 || !b4) {// 有一块没覆盖，就是没覆盖
					return false;
				}
			}
		}
		return true;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
	}

}
